//
//  DBParserRule.m
//  parser
//
//  Created by Daniel Braun on 26/05/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "DBParserRule.h"
#import "DBParser.h"
#import "DBLexer.h"

@implementation DBParserRule

- (void) dealloc {
	[nextSeq release];
	[super dealloc];
}

- (id) initWithAction:(SEL)act
{
	int i;
	self=[super init];
	if (self) {
		action=act;
		for (i=0; i<_DBP_MAX_LA; i++) tokens[i]=-1;
	}
	return self;
}
- (DBParserRule *) instantiateRule
{
	return self;
}

- (DBParserRule *) appendSeq: (DBParserRule*) r
{
	NSAssert([r isKindOfClass:[DBParserRule class]],@"expecting a DBParserRule");
	if (!nextSeq) {
		nextSeq=[r retain];
	}
	else [nextSeq appendSeq:r];
	return self;
}


- (DBParserRule *) nextSeq
{
	return nextSeq;
}

- (void) invokeWithParser:(DBParser *)p
{
	if ([p _tlookAhead0]==tokens[0]) {
		[self beginWithParser:p];
		[self matchedWithParser:p];
	} else {
		[p _nomatch:self];
	}
}	

- (void) matchedWithParser:(DBParser *)p consume:(BOOL)c
{
	if (action) [p _triggerAction:action];
	if (c) [p _consume];
	[nextSeq invokeWithParser:p];
}
- (void) matchedWithParser:(DBParser *)p
{
	[self matchedWithParser:p consume:NO];
}
- (void) beginWithParser:(DBParser *)p
{
}

- (void) preProcess
{
	[nextSeq preProcess];
	[self appendTokensFrom:nextSeq];
}

- (int *) tokens
{
	return tokens;
}

- (void) appendTokensFrom:(DBParserRule *)r
{
	int i;
	int j;
	if (!r) return;
	int *t=[r tokens];
	for (i=0, j=0; i<_DBP_MAX_LA; i++) {
		if (tokens[i]>=0) continue;
		tokens[i]=t[j++];
	}
}
@end
